﻿Imports System.Text.RegularExpressions
Imports System.ComponentModel
Imports OnlineVideos.Sites.WebSite
Imports MediaPortal.GUI.Library
Imports MediaPortal.Dialogs
Imports System.Net

' TODO: This needs to be redesigned so that the video list is what's now appearing as sub-categories and have what now appears as the video list appear as the PlayBack options.
Public Class FirstRowUtil
    Inherits SiteUtilBase

    Private Enum Sections
        MainMenu
        Channel
        VideoQuality
    End Enum

    Private cc As CookieContainer
    Private baseURL As String = "http://www.firstrowsports.eu/"

    Private Sub GetBaseCookie(forURL As String)
        WebCache.Instance(forURL) = Nothing
        Dim tmpcc As CookieContainer = New CookieContainer()
        GetWebData(baseURL, tmpcc)

        cc = New CookieContainer()
        Dim ccol As CookieCollection = tmpcc.GetCookies(New Uri(baseURL))
        For Each c As Cookie In ccol
            cc.Add(c)
        Next
    End Sub

    Public Overrides Function DiscoverDynamicCategories() As Integer
        GetBaseCookie(baseURL)

        Dim webData = GetWebData(baseURL, cc)

        If Settings.Categories Is Nothing Then Settings.Categories = New BindingList(Of Category)

        Dim m = Regex.Match(webData, "<a\shref=""(?<url>[^""]*)"">(?<title>[^<]*)</a>\s</li>")
        While m.Success
            Dim newCat = New RssLink()
            newCat.Name = Web.HttpUtility.HtmlDecode(m.Groups("title").Value)
            newCat.Url = baseURL + m.Groups("url").Value
            newCat.HasSubCategories = True
            newCat.Other = Sections.MainMenu

            Settings.Categories.Add(newCat)

            m = m.NextMatch()
        End While

        Settings.DynamicCategoriesDiscovered = (Settings.Categories.Count > 0)

        Return Settings.Categories.Count
    End Function

    Public Overrides Function DiscoverSubCategories(parentCategory As Category) As Integer
        Dim cats As New List(Of Category)
        Dim link As RssLink = CType(parentCategory, RssLink)
        Dim webData = GetWebData(link.Url, cc)
        Dim regExp = "<a\sclass=""accordlink""\s*href='(?<url>[^']*)'\starget=""_blank"">\s<img\sclass=""chimg""\salt=""(?<title>[^""]*)""\ssrc=""(?<thumb>[^""]*)""/>"

        Dim m = Regex.Match(webData, regExp)
        While m.Success
            Dim newCat = New RssLink()
            newCat.Name = m.Groups("title").Value
            newCat.Url = baseURL + m.Groups("url").Value
            newCat.Thumb = baseURL + m.Groups("thumb").Value
            newCat.Other = Sections.Channel
            newCat.HasSubCategories = False

            cats.Add(newCat)

            m = m.NextMatch()
        End While

        parentCategory.SubCategories = cats
        parentCategory.SubCategories.ForEach(Sub(cat) cat.ParentCategory = parentCategory)
        parentCategory.SubCategoriesDiscovered = (cats.Count > 0)

        Return parentCategory.SubCategories.Count
    End Function

    Public Overrides Function getVideoList(category As Category) As System.Collections.Generic.List(Of VideoInfo)
        Dim videos As New List(Of VideoInfo)
        Dim link As RssLink = CType(category, RssLink)
        Dim webData = GetWebData(link.Url, cc)
        Dim regExp = "<a\sstyle='font-size:12pt;color:limef;'\s*title='(?<title>[^']*)'href='(?<url>[^']*)'>"

        Dim m = Regex.Match(webData, regExp)
        While m.Success
            Dim newVideo = New VideoInfo()
            newVideo.Title = m.Groups("title").Value
            newVideo.VideoUrl = baseURL + m.Groups("url").Value
            newVideo.ImageUrl = baseURL + m.Groups("thumb").Value
            newVideo.Other = Sections.VideoQuality

            videos.Add(newVideo)

            m = m.NextMatch()
        End While

        Return videos
    End Function

    Public Overrides Function getUrl(video As VideoInfo) As String
        GetBaseCookie(video.VideoUrl)
        Dim webData As String = GetWebData(video.VideoUrl, cc)
        Dim scriptUrl As String = ""

        Dim m = Regex.Match(webData, "document\.write\(\sunescape\(\s'(?<url>[^']*)'\s\)\s\);")
        If m.Success Then
            Dim script = Web.HttpUtility.UrlDecode(m.Groups("url").Value)
            If m.Success Then
                m = Regex.Match(script, "src='(?<url>[^']*)'")
                scriptUrl = m.Groups("url").Value
            End If
        End If

        If Not m.Success Then
            m = Regex.Match(webData, "document\.write\(unescape\('%3Cscript\stype=\\""text/javascript\\""\ssrc=""(?<url>[^\\]*)\\""%3E%3C/scr'\+'ipt%3E'\)\);")
            If m.Success Then scriptUrl = m.Groups("url").Value
        End If

        '' TV
        'If Not m.Success Then
        '    m = Regex.Match(webData, "<script\ssrc=""(?<url>[^""]*)""\stype=""text/javascript"">")
        '    While m.Success
        '        If m.Groups("url").Value.Contains("ilive.to") Then
        '            scriptUrl = m.Groups("url").Value
        '            Exit While
        '        End If
        '        m = m.NextMatch()
        '    End While
        'End If

        'If Not webData.Contains("iframe") AndAlso webData.Contains("rtmp://") Then

        'End If

        'If scriptUrl.Contains("cache_buster") Then
        '    scriptUrl = scriptUrl.Replace("'+cache_buster+'", (New Random(Now.Millisecond)).Next().ToString())
        'End If

        'If webData.Contains("iframe") Then
        '    ' TV
        '    If scriptUrl <> "" Then webData = GetWebData(scriptUrl, cc)

        '    Dim iFrameURL = scriptUrl
        '    If Not webData.Contains("streamer=") Then
        '        m = Regex.Match(webData, "src='(?<script>[^']*)'")
        '        If Not m.Success Then m = Regex.Match(webData, "src=""(?<script>[^""]*)""")

        '        While m.Success
        '            If m.Groups("script").Value.Contains("width=") Then
        '                iFrameURL = m.Groups("script").Value
        '                Exit While
        '            End If
        '            m = m.NextMatch()
        '        End While

        '        webData = GetWebData(iFrameURL, cc)
        '    End If
        '    Dim p1 = webData.IndexOf("streamer=") + 9
        '    Dim p2 = webData.IndexOf("""", p1)
        '    Dim url = Web.HttpUtility.UrlDecode(webData.Substring(p1, p2 - p1))

        '    Dim filter = New MPUrlSourceFilter.RtmpUrl(url)
        '    filter.PlayPath = url.Split("&")(1).Split("=")(1)
        '    filter.Live = True
        '    If url.Contains("ilive.to") Then
        '        filter.App = "redirect"
        '        filter.FlashVersion = "WIN 11,0,1,152"
        '    End If
        '    filter.PageUrl = iFrameURL
        '    Debug.WriteLine(filter.ToString())
        '    Return filter.ToString()
        'Else
        webData = GetWebData(scriptUrl, cc)
        m = Regex.Match(webData, "document\.write\(\sunescape\(\s'(?<script>[^']*)'\s\)\s\);")

        If m.Success Then
            webData = Web.HttpUtility.UrlDecode(m.Groups("script").Value)
            m = Regex.Match(webData, "src=(?<url>[^']*)")
            If m.Success Then
                Dim iframeUrl = m.Groups("url").Value
                Dim scriptUri = New Uri(scriptUrl)
                'iframeUrl = iframeUrl + "'" + scriptUri.Host + "'"
                iframeUrl = iframeUrl + "'embed.zonein.tv'"
                webData = GetWebData(iframeUrl, cc)
                Debug.WriteLine(webData)

                ' TODO: What now? What do we do now? eh?
            End If
        End If
        'End If

        ' http://serbianforum.org/internet/60172-internet-radio-i-televizija-1110-print.html

        Return ""
    End Function
End Class
